package com.smartresume.backend.controller;

import com.smartresume.backend.model.ResumeAnalysisRequest;
import com.smartresume.backend.model.ResumeAnalysisResponse;
import com.smartresume.backend.service.ResumeAnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 简历分析控制器 - 集成AI服务
 * 
 * @author SmartResume Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/resume")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:3000"}, allowCredentials = "true")
public class SimpleController {
    
    private static final Logger log = LoggerFactory.getLogger(SimpleController.class);

    @Autowired
    private ResumeAnalysisService resumeAnalysisService;

    @PostMapping("/analyze")
    public ResponseEntity<Map<String, Object>> analyzeResume(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String resumeText = request.get("resumeText");
            String industry = request.get("industry");
            
            if (resumeText == null || resumeText.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "简历内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 如果没有提供行业，默认为技术行业
            if (industry == null || industry.trim().isEmpty()) {
                industry = "technology";
            }
            
            log.info("收到简历分析请求，文本长度: {}, 目标行业: {}", resumeText.length(), industry);
            
            // 调用AI服务进行分析，传递行业参数
            ResumeAnalysisResponse aiResponse = resumeAnalysisService.analyzeResume(resumeText, industry);
            
            if (aiResponse.isSuccess()) {
                response.put("success", true);
                response.put("message", aiResponse.getMessage());
                response.put("keywords", aiResponse.getKeywords());
                response.put("strengths", aiResponse.getStrengths());
                response.put("weaknesses", aiResponse.getWeaknesses());
                response.put("suggestions", aiResponse.getSuggestions());
                response.put("matchScore", aiResponse.getMatchScore());
                
                log.info("简历分析完成，关键词数量: {}, 匹配度: {}", 
                        aiResponse.getKeywords() != null ? aiResponse.getKeywords().size() : 0,
                        aiResponse.getMatchScore());
            } else {
                response.put("success", false);
                response.put("message", aiResponse.getMessage());
                log.warn("简历分析失败: {}", aiResponse.getMessage());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("处理简历分析请求时发生异常", e);
            response.put("success", false);
            response.put("message", "服务器内部错误，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "SmartResume-AI Backend");
        health.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(health);
    }

    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getApiInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("service", "SmartResume-AI Backend");
        info.put("version", "1.0.0");
        info.put("description", "基于国产大模型的智能简历分析工具");
        info.put("endpoints", new String[]{
            "POST /api/resume/analyze - 分析简历",
            "GET /api/resume/health - 健康检查",
            "GET /api/resume/info - API信息"
        });
        return ResponseEntity.ok(info);
    }
}